<template>
  <div class="config-table-box" v-show="channels.length > 0">
    <el-tooltip content="新增曲线" placement="top">
      <el-button type="primary" icon="el-icon-plus" circle @click="onClickAddNew"></el-button>
    </el-tooltip>
    <el-tooltip content="画图" placement="top">
      <el-button type="success" icon="el-icon-picture" circle
        :disabled="config.length === 0"
        @click="onClickDraw"></el-button>
    </el-tooltip>
    <el-button :disabled="config.length === 0" @click="onSave">保存表格配置</el-button>
    <el-button @click="onLoad">读取表格配置</el-button>
    <el-button :disabled="isPolyDataEmpty" @click="onShowPoly">显示拟合数据</el-button>

    <el-dialog title="输入表格配置json" :visible.sync="isShowDialog">
      <el-input v-model="configJson" type="textarea"
        :autosize="rowSize"></el-input>
      <span slot="footer">
        <el-button type="primary" @click="onJsonRead">确定</el-button>
        <el-button @click="onJsonCancel">取消</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="mDialog.title" :visible.sync="mDialog.show">
      <el-input v-model="mDialog.message" type="textarea"
        :autosize="rowSize" readonly></el-input>
      <span slot="footer">
        <el-button type="primary" @click="onClickCopy">复制到剪贴板</el-button>
      </span>
    </el-dialog>

    <el-table :data="config" style="width: 100%">
      <!-- 序号 -->
      <el-table-column type="index" width="50"></el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作" width="60">
        <template slot-scope="scope">
          <el-button type="danger" icon="el-icon-close" size="small" circle
            @click="onClickDelete(scope.$index)">
          </el-button>
        </template>
      </el-table-column>
      <!-- 名称 -->
      <el-table-column label="别名 (默认: 曲线+序号)" width="200">
        <template slot-scope="scope">
          <el-input v-model="scope.row.name" placeholder="默认: 曲线+序号"></el-input>
        </template>
      </el-table-column>
      <!-- X轴 -->
      <el-table-column label="X轴通道" width="160">
        <template slot-scope="scope">
          <el-select v-model="scope.row.xIndex" placeholder="请选择通道号">
            <el-option label="无 (数序)" :value="-1"></el-option>
            <el-option
              v-for="(item, index) in channels"
              :key="item.title"
              :label="item.title"
              :value="index">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <!-- Y轴 -->
      <el-table-column label="Y轴通道" width="160">
        <template slot-scope="scope">
          <el-select v-model="scope.row.yIndex">
            <el-option
              v-for="(item, index) in channels"
              :key="item.title"
              :label="item.title"
              :value="index">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <!-- 开始 -->
      <el-table-column label="开始序号" width="200">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.begin"
            :min="baseIndex" :max="baseIndex + channels[0].data.length - 2"></el-input-number>
        </template>
      </el-table-column>
      <!-- 结束 -->
      <el-table-column label="结束序号" width="200">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.end"
            :min="scope.row.begin + 1"
            :max="baseIndex + channels[0].data.length - 1">
          </el-input-number>
        </template>
      </el-table-column>
      <!-- 颜色 -->
      <el-table-column label="颜色" width="60">
        <template slot-scope="scope">
          <el-color-picker v-model="scope.row.color" size="small"></el-color-picker>
        </template>
      </el-table-column>
      <!-- 拟合 -->
      <el-table-column label="拟合 (0为不拟合)" width="200">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.poly" :min="0" :max="8"></el-input-number>
        </template>
      </el-table-column>
      <!-- 转换 -->
      <el-table-column label="是否转换" width="100">
        <template slot-scope="scope">
          <el-select v-model="scope.row.change">
            <el-option label="无" value="none"></el-option>
            <el-option label="X轴" value="x"></el-option>
            <el-option label="Y轴" value="y"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <!-- 公式 -->
      <el-table-column label="转换公式 (例子: 3.1*x^2 + x + 1.1)">
        <template slot-scope="scope">
          <el-input v-model="scope.row.formula"
            placeholder="例子: 3*x^3 + 2*x^2 + x + 5"
            :disabled="scope.row.change === 'none'"></el-input>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  props: {
    channels: Array,
    polyData: Array,
    baseIndex: Number,
  },

  watch: {
    channels() {
      this.config = [];
    },
  },

  computed: {
    isPolyDataEmpty() {
      return this.polyData.length === 0;
    },
  },

  data() {
    return {
      config: [],
      isShowDialog: false,
      configJson: '',
      mDialog: {
        show: false,
        title: '',
        message: '',
      },
      rowSize: {
        maxRows: 8,
      },
    };
  },

  methods: {
    onClickAddNew() {
      const item = {
        name: '',
        xIndex: 0,
        yIndex: 1,
        begin: this.baseIndex,
        end: this.baseIndex + this.channels[0].data.length,
        color: this.getRandomColor(),
        poly: 0,
        change: 'none',
        formula: '',
      };
      this.config.push(item);
    },
    onClickDraw() {
      const curves = this.config.map((c, i) => {
        const begin = c.begin - this.baseIndex;
        const end = c.end + 1 - this.baseIndex;

        let yData = this.channels[c.yIndex].data.slice(begin, end);
        let xData;
        if (c.xIndex === -1) {
          xData = yData.map((y, yi) => yi);
        } else {
          xData = this.channels[c.xIndex].data.slice(begin, end);
        }

        if (c.change === 'x' && c.xIndex !== -1) {
          const ff = c.formula.replace(/x\^/g, 'x**');
          // eslint-disable-next-line
          const changeData = xData.map(x => eval(ff));
          xData = changeData;
        } else if (c.change === 'y') {
          const ff = c.formula.replace(/x\^/g, 'x**');
          // eslint-disable-next-line
          const changeData = yData.map(x => eval(ff));
          yData = changeData;
        }

        const curve = {
          name: c.name === '' ? `曲线${i + 1}` : c.name,
          color: c.color,
          poly: c.poly,
          data: xData.map((x, ix) => [x, yData[ix]]),
        };

        return curve;
      });

      this.$emit('draw', curves);
    },
    getRandomColor() {
      const colors = [];
      for (let i = 0; i < 3; i += 1) {
        colors.push(Math.floor(Math.random() * 255));
      }

      return `rgb(${colors[0]}, ${colors[1]}, ${colors[2]})`;
    },
    onClickDelete(index) {
      this.config.splice(index, 1);
    },
    onSave() {
      this.mDialog.title = '保存配置';
      this.mDialog.message = JSON.stringify(this.config);
      this.mDialog.show = true;
    },
    onLoad() {
      this.configJson = '';
      this.isShowDialog = true;
    },
    onJsonRead() {
      this.isShowDialog = false;
      try {
        this.config = JSON.parse(this.configJson);
      } catch (e) {
        this.$message({
          message: `转化错误: ${e.message}`,
          type: 'error',
          center: true,
        });
      }
    },
    onJsonCancel() {
      this.isShowDialog = false;
    },
    onShowPoly() {
      this.mDialog.title = '拟合数据';
      this.mDialog.message = this.polyData.join('\r\n');
      this.mDialog.show = true;
    },
    onClickCopy() {
      this.$copyText(this.mDialog.message)
        .then(() => {
          this.$message({
            message: '复制成功',
            type: 'success',
          });
        })
        .catch(() => {
          this.$message({
            message: '复制失败',
            type: 'error',
          });
        });
    },
  },
};
</script>

<style scoped>
.config-table-box {
  border: 1px dashed lightgray;
  margin-top: 10px;
  padding: 8px;
}
</style>
